import { useEffect, useState } from 'react';
import { Input, Tabs, Card, Tag, Button, Pagination, Modal, message } from "antd";
import {
    SearchOutlined,
    EditOutlined,
    CodeOutlined,
    BarChartOutlined,
    BookOutlined,
    BgColorsOutlined,
    LineChartOutlined,
    TranslationOutlined,
    AppstoreOutlined,
    BulbOutlined
} from '@ant-design/icons';
import './Dict.css';
import { getCategories, getPromptList } from '../api/dict.js'
import { useNavigate } from 'react-router-dom';

const { Meta } = Card;
const { messageApi } = message;

// 根据分类获取对应图标
const getIconByCategory = (category) => {
    const iconMap = {
        '写作': <EditOutlined style={{ fontSize: '48px', color: '#1890ff' }} />,
        '编程': <CodeOutlined style={{ fontSize: '48px', color: '#52c41a' }} />,
        '商业': <BarChartOutlined style={{ fontSize: '48px', color: '#fa8c16' }} />,
        '教育': <BookOutlined style={{ fontSize: '48px', color: '#722ed1' }} />,
        '设计': <BgColorsOutlined style={{ fontSize: '48px', color: '#eb2f96' }} />,
        '数据': <LineChartOutlined style={{ fontSize: '48px', color: '#13c2c2' }} />,
        '翻译': <TranslationOutlined style={{ fontSize: '48px', color: '#f5222d' }} />,
        '产品': <AppstoreOutlined style={{ fontSize: '48px', color: '#faad14' }} />
    };

    return iconMap[category] || <BulbOutlined style={{ fontSize: '48px', color: '#1890ff' }} />;
};

export default function Dict() {

    const navigate = useNavigate()
    //使用此模板对话框
    const [isModalOpen, setIsModalOpen] = useState(false);

    const [usePrompt, setUsePrompt] = useState(null)

    const [formData, setFormData] = useState({})

    const handleInputChange = (event) => {
        const { name, content } = event;
        setFormData((prevFormData) => ({
            ...prevFormData,
            [name]: content,
        }));

    }
    const showModal = (prompt) => {
        console.log(prompt);
        setUsePrompt(prompt)
        setIsModalOpen(true);
    };

    // 直接使用模板跳转到对话页面
    const useTemplate = (prompt) => {
        console.log('使用模板:', prompt);
        // 跳转到对话页面，并传递模板信息
        navigate('/', {
            state: {
                template: prompt,
                content: prompt.content,
                templateInfo: {
                    title: prompt.title,
                    description: prompt.description,
                    category: prompt.category,
                    tags: prompt.tags,
                    templateKeys: prompt.templateKeys
                }
            }
        });
    };


    const replaceKeyword = (content, keywords) => {
        return content.replace(/\$\{(\w+)\}/g, (match, key) => {
            return keywords[key] !== undefined ? keywords[key] : match;
        });
    };

    const handleOk = async () => {
        // 先进行替换操作（使用当前表单数据）
        const templateContent = replaceKeyword(usePrompt.content, formData);

        // 再清空表单
        setFormData({});

        // 后续操作
        console.log(templateContent);
        navigate('/', {
            state: {
                content: templateContent
            }
        })

        setIsModalOpen(false);
    };

    const handleCancel = () => {
        setFormData({});
        setIsModalOpen(false);

    };


    const [categories, setCategories] = useState([]);
    //获取分类
    useEffect(() => {
        const fetchCategories = async () => {
            try {
                const res = await getCategories()
                console.log('分类响应完整结构:', JSON.stringify(res, null, 2));
                console.log('res.data:', JSON.stringify(res.data, null, 2));
                console.log('res.data.code:', res.data?.code);
                console.log('res.data.data:', JSON.stringify(res.data?.data, null, 2));

                // 后端返回结构：{code: 0, data: [...], message: ""}
                if (res && res.data && res.data.code === 0 && res.data.data) {
                    console.log('分类数据解析成功:', res.data.data);
                    setCategories(['全部', ...res.data.data])
                } else {
                    console.error('分类数据格式错误:', res);
                    setCategories(['全部']);
                }

            } catch (error) {
                console.error('获取分类失败:', error);
                messageApi.error('获取分类失败')
                setCategories(['全部']);
            }
        }
        fetchCategories();

    }, [])

    //获取提示词模板

    const [loading, setLoading] = useState(false);
    const [searchText, setSearchText] = useState('');
    const [prompts, setPrompts] = useState([]);
    const [total, setTotal] = useState(0);
    const [currentPage, setCurrentPage] = useState(1);
    const [activeKey, setActiveKey] = useState('全部');
    const pageSize = 8; // 每页显示8个卡片

    // 解析方法
    const parseTags = (tagString) => {
        try {
            if (!tagString) return [];

            // 如果是逗号分隔的字符串，直接分割
            if (typeof tagString === 'string' && !tagString.startsWith('[')) {
                return tagString.split(',').map(tag => tag.trim()).filter(tag => tag);
            }

            // 如果是JSON数组格式，尝试解析
            if (typeof tagString === 'string' && tagString.startsWith('[')) {
                // 1. 替换单引号为双引号
                const jsonString = tagString
                    .replace(/'/g, '"')
                    .replace(/\[/g, '[')
                    .replace(/\]/g, ']');

                // 2. 解析为数组
                return JSON.parse(jsonString);
            }

            // 如果已经是数组，直接返回
            if (Array.isArray(tagString)) {
                return tagString;
            }

            return [];
        } catch (error) {
            console.error('标签解析失败:', error, tagString);
            return []; // 返回空数组作为兜底
        }
    };

    const fetchPrompts = async (category = 'all', page = 1) => {
        setLoading(true);
        try {
            const params = {
                current: page,
                pageSize: pageSize,
                category: category === '全部' ? null : category,
                title: searchText
            };

            const response = await getPromptList(params);
            console.log('提示词响应完整结构:', response);
            console.log('response.data:', response.data);
            console.log('response.data.code:', response.data?.code);
            console.log('response.data.data:', response.data?.data);
            console.log('response.data.data.records:', response.data?.data?.records);

            // 后端返回结构：{code: 0, data: {records: [...], total: 10}, message: ""}
            if (response && response.data && response.data.code === 0 && response.data.data && response.data.data.records) {
                const processedRecords = response.data.data.records.map(item => ({
                    ...item,
                    tags: parseTags(item.tags), // 直接解析为数组
                    templateKeys: parseTags(item.templateKeys)
                }));
                setPrompts(processedRecords);
                setTotal(response.data.data.total);
                setCurrentPage(page);
            } else {
                console.error('提示词数据格式错误:', response);
                setPrompts([]);
                setTotal(0);
                messageApi.error('获取提示词数据格式错误');
            }
        } catch (error) {
            console.error('获取提示词失败:', error);
            messageApi.error('获取提示词失败');
            setPrompts([]);
            setTotal(0);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchPrompts(activeKey, currentPage);

    }, [activeKey, currentPage, searchText])


    // 处理分类切换
    const handleTabChange = (key) => {
        setActiveKey(categories[key]);
        setCurrentPage(1); // 切换分类时重置页码
    };

    // 处理搜索
    const handleSearch = (e) => {
        setSearchText(e.target.value);
        setCurrentPage(1); // 搜索时重置页码
    };


    //获取当前活动key
    const getCurrentCategory = (key) => {
        return categories.findIndex((item) => item === key);
    }
    return (
        <div id="dict">
            {/* 使用模板对话弹窗 */}
            <div className='dict-modal'>
                <Modal
                    cancelText="取消"
                    okText="确定使用"
                    centered
                    title={`自定义模板：${usePrompt?.title || ''}`}
                    closable={{ 'aria-label': 'Custom Close Button' }}
                    open={isModalOpen}
                    onOk={handleOk}
                    onCancel={handleCancel}
                    width={600}
                >
                    <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f6f9fc', borderRadius: '6px', border: '1px solid #d1ecf1' }}>
                        <p style={{ margin: '0 0 8px 0', fontWeight: 'bold', color: '#0066cc' }}>📝 模板说明：</p>
                        <p style={{ margin: '0 0 8px 0', fontSize: '14px', color: '#666' }}>{usePrompt?.description}</p>
                        <p style={{ margin: '0', fontSize: '12px', color: '#999' }}>💡 请填写下面的变量，系统会自动替换模板中的占位符</p>
                    </div>

                    {
                        usePrompt?.templateKeys.map((item, index) => {
                            // 获取变量建议
                            const getPlaceholder = (variableName) => {
                                const suggestions = {
                                    'user_input': '例如：写一篇关于AI的文章',
                                    'topic': '例如：人工智能',
                                    'content': '例如：具体的内容或文本',
                                    'language': '例如：中文',
                                    'style': '例如：正式、专业',
                                    'audience': '例如：初学者',
                                    'format': '例如：列表、段落',
                                    'length': '例如：500字左右'
                                };
                                return suggestions[variableName] || `请输入${variableName}的具体内容`;
                            };

                            return <div key={index} style={{ marginTop: '16px' }}>
                                <div style={{ marginBottom: '8px', fontWeight: '500', color: '#333' }}>
                                    🔧 ${item}
                                </div>
                                <Input type="text"
                                    id={`key${index}`}
                                    name={item}
                                    placeholder={getPlaceholder(item)}
                                    value={formData[item]}
                                    onChange={(e) => handleInputChange({ name: item, content: e.target.value })}
                                    style={{ width: '100%' }}
                                />
                            </div>
                        })
                    }
                </Modal>
            </div>


            <div className="dict-header">
                <h1 className="dict-title">提示词库</h1>
                <p className="dict-subtitle">探索经典高效的AI提示词模板</p>

                <div className="dict-search">
                    <Input
                        placeholder="搜索提示词..."
                        prefix={<SearchOutlined />}
                        allowClear
                        size="large"
                        onChange={handleSearch}
                        value={searchText}
                    />
                </div>
            </div>


            <div className="dict-content">
                {
                    loading ? (
                        <div>加载中...</div>
                    ) : (
                        <Tabs
                            activeKey={getCurrentCategory(activeKey)}
                            onChange={handleTabChange}
                            size="large"
                            items={categories?.map((category, index) => ({
                                key: index,
                                label: category,
                                children: (
                                    <>
                                        {
                                            loading ? (
                                                <div>加载中...</div>
                                            ) : (
                                                <div className="prompt-grid">
                                                    {prompts?.map((prompt, index) => (
                                                        <div key={index} className="flip-card">
                                                            <div className="flip-card-inner">
                                                                {/* 正面 - 显示名字和图片 */}
                                                                <div className="flip-card-front">
                                                                    <div className="card-icon">
                                                                        {getIconByCategory(prompt.category)}
                                                                    </div>
                                                                    <h3 className="card-title">{prompt.title}</h3>
                                                                    <p className="card-category">{prompt.category}</p>
                                                                    <div className="card-tags">
                                                                        {prompt.tags && Array.isArray(prompt.tags) && prompt.tags.slice(0, 3).map((tag, i) => (
                                                                            <Tag key={i} className="card-tag">{tag}</Tag>
                                                                        ))}
                                                                    </div>
                                                                </div>

                                                                {/* 背面 - 显示详细介绍 */}
                                                                <div className="flip-card-back">
                                                                    <h3 className="back-title">{prompt.title}</h3>
                                                                    <p className="back-description">{prompt.description}</p>
                                                                    <div className="back-content">
                                                                        {prompt.content && prompt.content.length > 200
                                                                            ? prompt.content.substring(0, 200) + '...'
                                                                            : prompt.content || ''}
                                                                    </div>
                                                                    <div className="back-actions">
                                                                        <Button
                                                                            type="primary"
                                                                            onClick={() => useTemplate(prompt)}
                                                                            className="use-template-btn"
                                                                            style={{ marginRight: '8px' }}
                                                                        >
                                                                            直接使用
                                                                        </Button>
                                                                        <Button
                                                                            type="default"
                                                                            onClick={() => showModal(prompt)}
                                                                            className="custom-template-btn"
                                                                        >
                                                                            自定义
                                                                        </Button>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    ))}
                                                </div>
                                            )
                                        }
                                        <div className="pagination-wrapper">
                                            <Pagination
                                                current={currentPage}
                                                total={total}
                                                pageSize={pageSize}
                                                onChange={(page) => setCurrentPage(page)}
                                                showSizeChanger={false}
                                            />
                                        </div>
                                    </>
                                )
                            }))}
                        />
                    )
                }
            </div>
        </div>
    )
}
